//
//  ViewController.m
//  WeChatMoments
//
//  Created by Jiang on 2019/8/25.
//  Copyright © 2019 SilverFruity. All rights reserved.
//

#import "WeChatMomentsViewController.h"
#import "UserRelatedClient.h"
#import "HeaderRefreshTableView.h"

#import "MomentUserInfoHeaaderView.h"
#import "MomentSectionCell+ConfigureForMomentItem.h"
#import "MomentImagesCell+ConfigureForImageItems.h"
#import "MomentCommentCell+ConfigureForMomentItem.h"
#import "MomentFeatureCell.h"
#import <MJRefresh/MJRefresh.h>

@interface WeChatMomentsViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UserRelatedClient *client;
@property (weak, nonatomic) IBOutlet HeaderRefreshTableView *tableView;
@property (weak, nonatomic) IBOutlet MomentUserInfoHeaaderView *headerView;
@property (nonatomic, strong)MomentUser *user;
@property (nonatomic, strong)Pagination *pagination;
@property (nonatomic, strong)NSArray <MomentItem *> *allItems;
@property (nonatomic, strong)NSMutableArray <MomentItem *> *items;
@end
@implementation WeChatMomentsViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.client = [UserRelatedClient new];
    
    __weak typeof(self) weakSelf = self;
    
    self.tableView.tableFooterView = [UIView new];
    
    [self.tableView setHeaderRefreshSuperView:self.view];
    self.tableView.headerRefreshActionBlock = ^{
        [weakSelf loadDataWithPage:1];
    };
    self.tableView.mj_footer = [MJRefreshAutoStateFooter footerWithRefreshingBlock:^{
        [weakSelf loadDataWithPage:self.pagination.currentPage + 1];
    }];
    
    [self.client getUserInfoWithUserName:@"jsmith" plugin:[SFMapModelPlugin pluginWithModelClass:MomentUser.class] completion:^(NSHTTPURLResponse * _Nonnull response, MomentUser *user, NSError * _Nullable error) {
        self.user = user;
        self.headerView.usernameLabel.text = self.user.nick;
        [self.headerView.avatarImageView sp_setImageWithURL:[NSURL URLWithString:self.user.avatar]];
        [self.headerView.profileImageView sp_setImageWithURL:[NSURL URLWithString:self.user.profile_image]];
        [self loadAllData];
    }];
}
- (void)loadAllData{
    [self.client getMomentListWithUserName:self.user.username plugin:nil completion:^(NSHTTPURLResponse * _Nonnull response, NSArray <MomentItem *>*items, NSError * _Nullable error) {
        if (!error) {
            self.allItems = [items filter:^BOOL(NSUInteger index, MomentItem *Object) {
                return Object.content != nil || Object.images.count > 0;
            }];
            [self.tableView headerRefreshBeginRefresh];
        }
    }];
}
- (void)loadDataWithPage:(NSInteger)page{
    NSInteger size = 5;
    NSInteger offset = (page - 1) * size;
    NSArray <MomentItem *>*pageItems = [self.allItems copy];
    if (self.allItems.count > offset) {
        size = offset+size <= self.allItems.count ? size : self.allItems.count - offset;
        pageItems = [pageItems subarrayWithRange:NSMakeRange(offset, size)];
    }else{
        pageItems = [NSArray array];
    }
    Pagination *pagination = [Pagination new];
    pagination.currentPage = page;
    pagination.totoalCount = self.allItems.count;
    self.pagination = pagination;

    if (self.pagination.currentPage == 1) {
        self.items = [pageItems mutableCopy];
    }else{
        [self.items addObjectsFromArray:pageItems];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView headerRefreshEndRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    });
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.items.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    MomentItem *item = self.items[section];
    return 3 + (item.comments.count > 1 ? 1 : 0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MomentItem *item = self.items[indexPath.section];
    if (indexPath.row == 0) {
        MomentSectionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MomentSectionCell"];
        [cell configureForMomentItem:item];
        return cell;
    }else if (indexPath.row == 1){
        MomentImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MomentImagesCell"];
        [cell configureForImageItems:item.images];
        return cell;
    }else if (indexPath.row == 2){
        MomentFeatureCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MomentFeatureCell"];
        cell.timeLabel.text = @"xx分钟前";
        return cell;
    }
    
    MomentCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MomentCommentCell"];
    [cell configureForMomentItem:item];
    return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, 0.5)];
    view.backgroundColor = [UIColor lightGrayColor];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.5;
}
@end
 
